package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.dtos.PageResponseResult;
import com.heima.model.admin.dtos.ResponseResult;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        /**
         * 查询列表
         * @param dto
         * @return
         */
        // 1 参数检查
        if (dto == null) {
            throw new CustomException ( AppHttpCodeEnum.PARAM_INVALID );
        }
        dto.checkParam ();

        // 2 条件查询
        Page<ApUserRealname> page = new Page<> ( dto.getPage (), dto.getSize () );
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper ();

        if (dto.getStatus () != null) {
            lambdaQueryWrapper.eq ( ApUserRealname::getStatus, dto.getStatus () );
        }

        IPage<ApUserRealname> resultPage = page ( page, lambdaQueryWrapper );

        // 3 返回结果
        return new PageResponseResult ( dto.getPage (), dto.getSize (),
                resultPage.getTotal (), resultPage.getRecords () );

    }

    @Autowired
    ApUserMapper apUserMapper;

    /**
     * @param dto
     * @param status 2 审核失败   9 审核成功
     * @return
     */
    @GlobalTransactional(timeoutMills = 60000,rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //检查参数
        if (dto == null || dto.getId () == null) {
            CustException.cust ( AppHttpCodeEnum.PARAM_INVALID, "实名认证信息id参数错误" );
        }
        //查询实名认证信息
        ApUserRealname userRealname = getById ( dto.getId () );
        if (userRealname == null) {
            CustException.cust ( AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证信息不存在" );
        }
        //判断当前实名认证的状态
        if (userRealname.getStatus ().intValue () != 1) {
            CustException.cust ( AppHttpCodeEnum.DATA_NOT_ALLOW, "审核状态错误" );
        }
        //查询相关的ap_user
        ApUser apUser = apUserMapper.selectById ( userRealname.getUserId () );
        if (apUser == null) {
            CustException.cust ( AppHttpCodeEnum.DATA_NOT_EXIST, "app用户不存在" );
        }
        //修改实名认证的信息
        userRealname.setUpdatedTime ( new Date () );
        userRealname.setStatus ( status );
        if (StringUtils.isNotBlank ( dto.getMsg () )) {
            userRealname.setReason ( dto.getMsg () );
        }
        updateById ( userRealname );//修改认证状态
        //状态为2
        if (status.intValue () == 2) {
            return ResponseResult.okResult ();
        }
        //状态为9，开通自媒体账户
        if (status.intValue () == 9) {
            return ResponseResult.okResult ();
        }
        WmUser wmUser = createWnUser ( apUser );


        //创建作者信息
        createAuthor ( apUser, wmUser );

        return ResponseResult.okResult ();
    }

    @Autowired
    ArticleFeign articleFeign;
    /**
     * 创建作者信息
     *
     * @param apUser
     * @param wmUser
     */
    private void createAuthor(ApUser apUser, WmUser wmUser) {
        ResponseResult<ApAuthor> findResult = articleFeign.findByUserId ( apUser.getId () );
        if (findResult.getCode ().intValue () != 0) {
            CustException.cust ( AppHttpCodeEnum.REMOTE_SERVER_ERROR, findResult.getErrorMessage () );
        }
        ApAuthor author = findResult.getData ();
        if (author != null) {
            CustException.cust ( AppHttpCodeEnum.DATA_NOT_EXIST, "作者账户已存在" );
        }
        author = new ApAuthor ();
        author.setName ( apUser.getName () );
        author.setType ( 2 );
        author.setUserId ( apUser.getId () );
        author.setCreatedTime ( apUser.getCreatedTime () );
        author.setWmUserId ( wmUser.getId () );
        ResponseResult saveResult = articleFeign.save ( author );
        if (findResult.getCode ().intValue () != 0) {
            CustException.cust ( AppHttpCodeEnum.REMOTE_SERVER_ERROR, findResult.getErrorMessage () );
        }
    }

    @Autowired
    WemediaFeign wemediaFeign;

    /**
     * 创建自媒体账户
     *
     * @param apUser
     * @return
     */
    private WmUser createWnUser(ApUser apUser) {
        //使用feign根据用户名称查询自媒体账户
        ResponseResult<WmUser> findResult = wemediaFeign.findByName ( apUser.getName () );
        if (findResult.getCode ().intValue () != 0) {
            CustException.cust ( AppHttpCodeEnum.REMOTE_SERVER_ERROR, findResult.getErrorMessage () );
        }
        WmUser wnUser = findResult.getData ();


        if (wnUser != null) {
            CustException.cust ( AppHttpCodeEnum.DATA_NOT_EXIST, "自媒体账户已存在" );
        }

        //不存在创建自媒体
        WmUser wmUser = new WmUser ();
        wnUser.setApUserId ( apUser.getId () );
        wnUser.setName ( apUser.getName () );
        wnUser.setPassword ( apUser.getPassword () );
        wnUser.setSalt ( apUser.getSalt () );
        wnUser.setImage ( apUser.getImage () );
        wnUser.setPhone ( apUser.getPhone () );
        wnUser.setStatus ( 9 );
        wnUser.setType ( 0 );
        wnUser.setCreatedTime ( new Date () );
        ResponseResult<WmUser> saveResult = wemediaFeign.save ( wmUser );
        if (findResult.getCode ().intValue () != 0) {
            CustException.cust ( AppHttpCodeEnum.REMOTE_SERVER_ERROR, findResult.getErrorMessage () );
        }
        return saveResult.getData ();
    }
}
